﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Jlvier.TaobaoShowcase.Service;
using Timer=System.Threading.Timer;

namespace ShowWindowIntelligence
{
    public delegate void RecommendationHandler();

    public partial class SimplifiedForm : Form
    {
        private const int MaxMessageCount = 1000;
        private Timer timer;

        public SimplifiedForm()
        {
            InitializeComponent();
        }

        private int TimeInterval
        {
            get { return Convert.ToInt32(numericInterval.Value * 1000 * 60); }
        }

        #region Event handlers

        private void OnTimerAutoRunTick(object state)
        {            
            SetControlAvailability(false);
            RecommendProduct();
            SetControlAvailability(true);
        }
        private void OnIntervalChanged(object sender, EventArgs e)
        {
            if (null == timer) return;
            timer.Change(0, TimeInterval);
        }
        private void OnExitClick(object sender, EventArgs e)
        {
            Close();
        }
        private void OnRunNowClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                RecommendProduct();
            }
            finally 
            {
                Cursor = Cursors.Default; 
            }
        }
        private void OnAutoRunChecked(object sender, EventArgs e)
        {
            if (!checkBoxAutoRecommend.Checked)
            {
                timer.Dispose();
            }
            timer = new Timer(OnTimerAutoRunTick,null,TimeInterval,TimeInterval);
        }
        private void OnDialogSizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                Visible = false;
                notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
                notifyIcon.BalloonTipTitle = "I am here";
                notifyIcon.BalloonTipText = "The app will go on working.";
                notifyIcon.ShowBalloonTip(0);
            }
        }
        private void OnNotifyIconDoubleClick(object sender, MouseEventArgs e)
        {
            Visible = true;
            WindowState = FormWindowState.Normal;
        }

        #endregion

        private void RecommendProduct()
        {
            try
            {
                APIInvokeMonitor.Instance.Clear();
                Notify(SR.RecommendationStarted);
                IShowWindowRule rule = new WillDelist(new List<Product>(), new List<Product>());
                rule.Apply();
                Notify(SR.RecommendationCompleted);
            }
            catch (RecommendationOverloadException)
            {
                Notify(SR.RecommendationCompleted);
            }
            catch (Exception ex)
            {
                Notify(SR.ErrorOccuredWhenRecommendProduct(ex.Message));
            }
            finally
            {
                Notify(string.Format("{0} apis were invoked", APIInvokeMonitor.Instance.Count));
            }
        }
        private void Notify(string message)
        {
            RecommendationHandler errorHandler = delegate
                                           {
                                               if (listBoxStatus.Items.Count >MaxMessageCount) listBoxStatus.Items.Clear();
                                               listBoxStatus.Items.Add(string.Format("{0} {1}", DateTime.Now, message));
                                           };
            Execute(errorHandler);
        }
        private void SetControlAvailability(bool enabled)
        {
            RecommendationHandler action = delegate
            {
                buttonRunNow.Enabled = enabled;
                buttonExit.Enabled = enabled;
                numericInterval.Enabled = enabled;
                checkBoxAutoRecommend.Enabled = enabled;
            };
            Execute(action);
        }
        private void Execute(RecommendationHandler action)
        {
            if (InvokeRequired)
            {
                Invoke(action);
            }
            else
            {
                action();
            }
        }
    }
}
